<template>
  <div class="devicePreload-add-update-component">
    <el-dialog
      v-if="modelValue.visible"
      v-model="modelValue.visible"
      :title="
        !modelValue.form.id
          ? `新增${modelValue.title}`
          : `修改${modelValue.title}`
      "
      width="550px"
    >
      <div style="padding-right: 50px; padding-top: 20px">
        <el-form
          :model="modelValue.form"
          :rules="modelValue.rules"
          ref="addEditRef"
          :label-width="100"
        >
          <el-form-item label="预部署编码" prop="code">
            <div style="display: flex; width: 100%">
              <el-input
                style="flex: 1; margin-right: 10px"
                placeholder="请输入预部署编码"
                v-model="modelValue.form.code"
                autocomplete="off"
              />
              <el-button type="primary" @click="generateCode"
                >生成预部署码</el-button
              >
            </div>
          </el-form-item>
          <el-form-item label="选择门店" prop="storeId">
            <el-select-v2
              v-model="modelValue.form.storeId"
              placeholder="请选择门店"
              filterable
              :options="modelValue.storeList"
              :props="{
                label: 'name',
                value: 'id',
              }"
              @change="selectStore"
            >
            </el-select-v2>
          </el-form-item>
          <el-form-item label="选择机台" prop="deviceIds">
            <el-select
              style="width: 100%"
              v-model="modelValue.form.deviceIds"
              placeholder="先选择门店再选择机台"
              multiple
            >
              <el-option
                v-for="option in deviceList"
                :key="option.number"
                :label="option.name"
                :value="option.number"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              :rows="3"
              placeholder="请输入备注"
              v-model="modelValue.form.remark"
              autocomplete="off"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer v-if="!modelValue.form.disabled">
        <span class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="ensure"> 确定 </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { ElMessage, FormInstance } from 'element-plus'
import {
  addDevicePreload,
  updateDevicePreload,
} from '@/api/dms-device-preload.api'
import { getNextCode } from '@/utils/SnowFlake.utils'
import { getDeviceInfoAllList } from '@/api/dms-device-info.api'

const props = defineProps(['modelValue'])
const addEditRef = ref<FormInstance>()

const generateCode = () => {
  let code = getNextCode()
  props.modelValue.form.code = 'PM' + code.substring(9)
}

const deviceList = ref([])
const requestDeviceInfoAllList = async (storeId: string) => {
  try {
    let list: any = await getDeviceInfoAllList({
      storeId,
    })
    deviceList.value = list || []
  } catch (err) {
    console.log(err)
  }
}

const selectStore = (val: any) => {
  let storeId = props.modelValue.form.storeId
  props.modelValue.form.deviceId = ''
  requestDeviceInfoAllList(storeId)
}

/***
 * 确认弹框
 */
const ensure = () => {
  let form = props.modelValue.form
  let storeId = props.modelValue.form.storeId

  let storeList = props.modelValue.storeList
  let findItem = storeList.find((item: any) => item.id == storeId)
  if (!findItem) {
    ElMessage({
      message: '请选择门店',
      type: 'error',
    })
    return
  } else {
    form.storeId = findItem.id
    form.storeNumber = findItem.number
    form.storeName = findItem.name
  }

  let deviceIds = props.modelValue.form.deviceIds
  if (Array.isArray(deviceIds)) {
    deviceIds = deviceIds.map((item: any) => {
      let findItem = deviceList.value.find((item2: any) => item2.number == item)
      return {
        id: findItem.id,
        name: findItem.name,
      }
    })

    deviceIds = JSON.stringify(deviceIds)
  }
  let formData = {
    code: form.code,
    storeId: form.storeId,
    storeNumber: form.storeNumber,
    storeName: form.storeName,
    deviceIds: deviceIds,
    status: form.status,
    deployStatus: form.deployStatus,
    remark: form.remark,
    expires: form.expires,
  }

  if (!addEditRef.value) return
  addEditRef.value.validate((valid, fields) => {
    if (valid) {
      if (form.id) {
        updateDevicePreload({
          ...formData,
          id: form.id,
        })
          .then((res) => {
            cancel()
            ElMessage({
              message: props.modelValue.title + '修改成功',
              type: 'success',
            })
            if (props.modelValue.refreshDataList) {
              props.modelValue.refreshDataList()
            }
          })
          .catch((err) => {
            ElMessage({
              message: err.msg || err,
              type: 'error',
            })
          })
        return
      }

      addDevicePreload(formData)
        .then((res) => {
          cancel()
          ElMessage({
            message: props.modelValue.title + '新增成功',
            type: 'success',
          })
          if (props.modelValue.refreshDataList) {
            props.modelValue.refreshDataList()
          }
        })
        .catch((err) => {
          ElMessage({
            message: err.msg || err,
            type: 'error',
          })
        })
    }
  })
}

/***
 * 取消弹框
 */
const cancel = () => {
  props.modelValue.visible = false
}
</script>
<style lang="scss" scoped></style>
